// Copyright (c) 2023 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::assist_string::to_assist_string;
use crate::output::write_content_replace_escape;
use crate::{OtherError, XmlError};
use serde::{ser, Serialize};
use std::io::Write;

/// A data format that can serialize any data structure supported by Serde.
struct Serializer<W: Write> {
    writer: W,
    tag_stack: Vec<String>,
    tag_stack_top: usize,
    element_num: Vec<usize>,
    element_index: Vec<usize>,
}

impl<W: Write> Serializer<W> {
    fn new(writer: W) -> Self {
        Serializer {
            writer,
            tag_stack: Vec::new(),
            tag_stack_top: 0,
            element_num: Vec::new(),
            element_index: Vec::new(),
        }
    }

    pub(crate) fn add_tag(&mut self, tag_name: String) -> Result<(), XmlError> {
        self.tag_stack.push(tag_name);
        self.tag_stack_top += 1;
        Ok(())
    }

    pub(crate) fn pop_tag(&mut self) -> Result<(), XmlError> {
        self.tag_stack.pop();
        self.tag_stack_top -= 1;
        Ok(())
    }

    pub(crate) fn obtain_current_tag(&mut self) -> Result<String, XmlError> {
        if self.tag_stack_top != self.tag_stack.len() {
            return Err(XmlError::from(OtherError::IncorrectStackLayers));
        }
        Ok(self.tag_stack[self.tag_stack_top - 1].clone())
    }

    pub(crate) fn current_tag_start(&mut self) -> Result<(), XmlError> {
        self.writer.write_all(b"<")?;
        let cur_tag = self.obtain_current_tag()?;
        self.writer.write_all(cur_tag.as_bytes())?;
        self.writer.write_all(b">")?;
        Ok(())
    }

    pub(crate) fn current_tag_end(&mut self) -> Result<(), XmlError> {
        self.writer.write_all(b"</")?;
        let cur_tag = self.obtain_current_tag()?;
        self.writer.write_all(cur_tag.as_bytes())?;
        self.writer.write_all(b">")?;
        Ok(())
    }

    pub(crate) fn add_seq_count(&mut self, len: usize) -> Result<(), XmlError> {
        self.element_num.push(len);
        self.element_index.push(0);
        Ok(())
    }

    pub(crate) fn pop_seq_count(&mut self) -> Result<(), XmlError> {
        self.element_num.pop();
        self.element_index.pop();
        Ok(())
    }

    pub(crate) fn obtain_current_seq_len(&mut self) -> usize {
        let len = self.element_num.len();
        self.element_num[len - 1]
    }

    pub(crate) fn obtain_current_element_index(&mut self) -> usize {
        let len = self.element_index.len();
        self.element_index[len - 1]
    }

    pub(crate) fn update_current_element_index(&mut self) -> Result<(), XmlError> {
        let len = self.element_index.len();
        self.element_index[len - 1] += 1;
        Ok(())
    }
}

/// An auxiliary struct which implements Write trait used in 'to_string' function.
struct AuxiliaryWriter {
    output: Vec<u8>,
}

impl Write for AuxiliaryWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.output.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// ylong_xml::serializer_compact supports two functions to produce as output: 'to_string' and 'to_writer'.
///
/// The to_string function serialize an instance which implements the Serialize Trait to a string and return.
pub fn to_string<T: Serialize>(value: &T) -> Result<String, XmlError> {
    let mut writer = AuxiliaryWriter { output: Vec::new() };
    to_writer(value, &mut writer)?;
    Ok(unsafe { String::from_utf8_unchecked(writer.output) })
}

/// The to_writer function serialize an instance which implements the Serialize Trait and
/// writes result into the writer passed in by the user, which needs to implement the std::io::Write.
pub fn to_writer<T: Serialize, W: Write>(value: &T, writer: &mut W) -> Result<(), XmlError> {
    let mut serializer = Serializer::new(writer);
    serializer
        .writer
        .write_all(r#"<?xml version="1.0" encoding="UTF-8"?>"#.as_bytes())?;
    value.serialize(&mut serializer)?;
    Ok(())
}

impl<'a, W: Write> ser::Serializer for &'a mut Serializer<W> {
    // Using `Ok` to propagate the data structure around simplifies Serializers
    // which build in-memory data structures. Set 'ok=()' and write the serialization
    // result to the buffer contained by the instance.
    type Ok = ();

    // The error type when serializing an instance may occur.
    type Error = XmlError;

    // Associative type composite data structures, such as sequences and maps,
    // used to track other states at serialization time. In this case, no state
    // is required other than what is already stored in the Serializer struct.
    type SerializeSeq = Self;
    type SerializeMap = Self;
    type SerializeStruct = Self;
    type SerializeStructVariant = Self;
    type SerializeTuple = Self;
    type SerializeTupleStruct = Self;
    type SerializeTupleVariant = Self;

    // The following 12 methods take one of the base types of the data model
    // and map it to Xml by appending it to the output string.
    fn serialize_bool(self, v: bool) -> Result<(), XmlError> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    // Xml does not distinguish between integers of different sizes,
    // so all signed integers and all unsigned integers will be serialized in the same way.
    // Therefore, all integers are converted to 64-bit integers and serialized here.
    fn serialize_i8(self, v: i8) -> Result<(), XmlError> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i16(self, v: i16) -> Result<(), XmlError> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i32(self, v: i32) -> Result<(), XmlError> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i64(self, v: i64) -> Result<(), XmlError> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_u8(self, v: u8) -> Result<(), XmlError> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u16(self, v: u16) -> Result<(), XmlError> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u32(self, v: u32) -> Result<(), XmlError> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u64(self, v: u64) -> Result<(), XmlError> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    // Same way for floating-point types.
    fn serialize_f32(self, v: f32) -> Result<(), XmlError> {
        self.serialize_f64(f64::from(v))
    }

    fn serialize_f64(self, v: f64) -> Result<(), XmlError> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_char(self, v: char) -> Result<(), XmlError> {
        self.serialize_str(v.encode_utf8(&mut [0; 4]))
    }

    fn serialize_str(self, v: &str) -> Result<(), XmlError> {
        write_content_replace_escape(&mut self.writer, String::from(v))?;
        Ok(())
    }

    fn serialize_bytes(self, _v: &[u8]) -> Result<(), XmlError> {
        Ok(())
    }

    fn serialize_none(self) -> Result<(), XmlError> {
        self.serialize_unit()
    }

    fn serialize_some<T>(self, value: &T) -> Result<(), XmlError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<(), XmlError> {
        Ok(())
    }

    // Unit struct represents a named value that does not contain any data. Map it to Xml as "".
    fn serialize_unit_struct(self, name: &'static str) -> Result<(), XmlError> {
        self.writer.write_all(b"<")?;
        self.writer.write_all(name.as_bytes())?;
        self.writer.write_all(b"/>")?;
        Ok(())
    }

    // When serializing a unit variant (or any other kind of variant), formats
    // can choose whether to track it by index or by name. Binary formats
    // usually use index while human-readable formats usually use name.
    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str, // The name of the variant.
    ) -> Result<(), XmlError> {
        self.writer.write_all(b"<")?;
        self.serialize_str(variant)?;
        self.writer.write_all(b"/>")?;
        Ok(())
    }

    // Treat newtype structs as insignificant wrappers for the data they contain.
    fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<(), XmlError>
    where
        T: ?Sized + Serialize,
    {
        self.add_tag(String::from(name))?;
        self.current_tag_start()?;
        value.serialize(&mut *self)?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }

    // The newtype variant (and all other variant serialization methods)
    // specifically refers to the enumerated representation of the "externally tagged".
    //
    // Serialize it to Xml in externally tagged form as `<NAME> VALUE </NAME>`.
    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str, // The name of the variant.
        value: &T,             // The data contained within this newtype variant.
    ) -> Result<(), XmlError>
    where
        T: ?Sized + Serialize,
    {
        self.add_tag(String::from(variant))?;
        self.current_tag_start()?;
        value.serialize(&mut *self)?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }

    // The following is the serialization of compound types.
    // The start of the sequence, each value, and the end use three separate method calls.
    // The serializer can be able to support sequences for which the length is unknown up front.
    //
    // This one used to serialize the start of the sequence.
    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, XmlError> {
        let seq_len = len.unwrap();
        self.add_seq_count(seq_len)?;
        Ok(self)
    }

    // Tuples and sequences are represented similarly in Xml.
    // Some formats can represent tuples more efficiently by omitting the length.
    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, XmlError> {
        self.serialize_seq(Some(len))
    }

    // Tuple and sequences are represented similarly in Xml.
    fn serialize_tuple_struct(
        self,
        name: &'static str,
        len: usize, // The number of data fields that will be serialized.
    ) -> Result<Self::SerializeTupleStruct, XmlError> {
        self.add_tag(String::from(name))?;
        self.current_tag_start()?;
        self.serialize_seq(Some(len))
    }

    // This method used only for the externally tagged representation.
    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str, // The name of the variant.
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, XmlError> {
        self.serialize_seq(Some(len))?;
        self.add_tag(String::from(variant))?;
        self.current_tag_start()?;
        Ok(self)
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, XmlError> {
        Ok(self)
    }

    fn serialize_struct(
        self,
        name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, XmlError> {
        self.add_tag(String::from(name))?;
        self.current_tag_start()?;
        Ok(self)
    }

    // This used for the externally tagged representation.
    fn serialize_struct_variant(
        self,
        name: &'static str, // The name of the enum.
        _variant_index: u32,
        variant: &'static str, // The name of the variant.
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, XmlError> {
        self.add_tag(String::from(name))?;
        self.current_tag_start()?;
        self.add_tag(String::from(variant))?;
        self.current_tag_start()?;
        Ok(self)
    }
}

// The following 7 impls used to serialize compound types like sequences and maps.
// At the beginning of serializing such types, one call of Serializer method.
// Next, zero or more calls which serializes a single element of the compound type.
// Finally, one call to end the serializing of the compound type.
//
// This impl is SerializeSeq so these methods are called after calling 'serialize_seq' on Serializer.
impl<'a, W: Write> ser::SerializeSeq for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        if self.obtain_current_element_index() != 0 {
            self.current_tag_start()?;
        }
        value.serialize(&mut **self)?;
        if self.obtain_current_element_index() != self.obtain_current_seq_len() - 1 {
            self.current_tag_end()?;
        }
        self.update_current_element_index()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.pop_seq_count()?;
        Ok(())
    }
}

impl<'a, W: Write> ser::SerializeTuple for &'a mut Serializer<W> {
    // Tuple do not have name, just need to record seq count.
    type Ok = ();
    type Error = XmlError;

    fn serialize_element<T>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)?;
        if self.obtain_current_element_index() != self.obtain_current_seq_len() - 1 {
            self.writer.write_all(b" ")?;
        }
        self.update_current_element_index()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.pop_seq_count()?;
        Ok(())
    }
}

impl<'a, W: Write> ser::SerializeTupleStruct for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)?;
        if self.obtain_current_element_index() != self.obtain_current_seq_len() - 1 {
            self.writer.write_all(b" ")?;
        }
        self.update_current_element_index()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.pop_seq_count()?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }
}

impl<'a, W: Write> ser::SerializeTupleVariant for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_field<T>(&mut self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)?;
        if self.obtain_current_element_index() != self.obtain_current_seq_len() - 1 {
            self.writer.write_all(b" ")?;
        }
        self.update_current_element_index()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.pop_seq_count()?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }
}

impl<'a, W: Write> ser::SerializeMap for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_key<T>(&mut self, key: &T) -> Result<Self::Ok, XmlError>
    where
        T: ?Sized + Serialize,
    {
        self.add_tag(to_assist_string(key)?)?;
        self.current_tag_start()?;
        Ok(())
    }

    fn serialize_value<T>(&mut self, value: &T) -> Result<Self::Ok, XmlError>
    where
        T: ?Sized + Serialize,
    {
        value.serialize(&mut **self)?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }
}

// A structure is like a map where the keys are restricted to a compile-time constant string.
impl<'a, W: Write> ser::SerializeStruct for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        self.add_tag(to_assist_string(key)?)?;
        self.current_tag_start()?;
        value.serialize(&mut **self)?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }
}

impl<'a, W: Write> ser::SerializeStructVariant for &'a mut Serializer<W> {
    type Ok = ();
    type Error = XmlError;

    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        self.add_tag(to_assist_string(key)?)?;
        self.current_tag_start()?;
        value.serialize(&mut **self)?;
        self.current_tag_end()?;
        self.pop_tag()?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.current_tag_end()?; // End struct
        self.pop_tag()?;
        self.current_tag_end()?; // End enum
        self.pop_tag()?;
        Ok(())
    }
}

#[cfg(test)]
mod ut_serializer_compact {
    use crate::serializer_compact::{to_string, AuxiliaryWriter, Serializer};
    use serde::Serialize;
    use std::{collections::HashMap, io::Write};

    /// UT test to serialize simple types.
    ///
    /// # Title
    /// ut_serialize_simple
    ///
    /// # Brief
    /// 1.Uses `to_string` method to serialize simple types.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_serialize_simple() {
        let value: Option<u32> = None;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: Option<u32> = Some(123);
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value = true;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>true"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: i8 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: i16 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: i32 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: i64 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: u8 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: u16 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: u32 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: u64 = 123;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>123"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: f32 = 1.0;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>1"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value: f64 = 1.0;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>1"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value = 't';
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>t"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value = "abc";
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>abc"#;
        assert_eq!(to_string(&value).unwrap(), expected);

        let value = b"abc";
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?>97 98 99"#;
        assert_eq!(to_string(&value).unwrap(), expected);
    }

    /// UT test to serialize simple struct
    ///
    /// # Title
    /// ut_serialize_struct_simple
    ///
    /// # Brief
    /// 1.Uses `to_string` method to serialize simple struct.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_serialize_struct_simple() {
        #[derive(Serialize)]
        struct TestUnit;
        let test = TestUnit;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><TestUnit/>"#;
        assert_eq!(to_string(&test).unwrap(), expected);

        #[derive(Serialize)]
        struct TestNewtype(u32);
        let test = TestNewtype(123);
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><TestNewtype>123</TestNewtype>"#;
        assert_eq!(to_string(&test).unwrap(), expected);

        #[derive(Serialize)]
        struct TestTuple(u32, u32, bool);
        let test = TestTuple(123, 321, true);
        let expected =
            r#"<?xml version="1.0" encoding="UTF-8"?><TestTuple>123 321 true</TestTuple>"#;
        assert_eq!(to_string(&test).unwrap(), expected);

        #[derive(Serialize)]
        struct Student {
            name: String,
            id: u32,
            male: bool,
        }

        let stu = Student {
            name: String::from("Jack"),
            id: 1001,
            male: true,
        };
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><Student><name>Jack</name><id>1001</id><male>true</male></Student>"#;
        assert_eq!(to_string(&stu).unwrap(), expected);
    }

    /// UT test to serialize complex struct
    ///
    /// # Title
    /// ut_serialize_struct_complex
    ///
    /// # Brief
    /// 1.Uses `to_string` method to serialize complex struct.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_serialize_struct_complex() {
        #[derive(Serialize)]
        struct Test {
            int: u32,
            seq: Vec<&'static str>,
            tup: (i32, i32, i32),
        }

        let test = Test {
            int: 1,
            seq: vec!["a", "b"],
            tup: (1, 2, 3),
        };
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><Test><int>1</int><seq>a</seq><seq>b</seq><tup>1 2 3</tup></Test>"#;
        assert_eq!(to_string(&test).unwrap(), expected);
    }

    /// UT test to serialize enum
    ///
    /// # Title
    /// ut_test_enum_for_serializer
    ///
    /// # Brief
    /// 1.Uses `to_string` method to serialize enum.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_serialize_enum() {
        #[derive(Serialize)]
        enum E {
            Newtype(i32),
            Unit,
            Struct { a: u32 },
            Tuple(u32, u32),
        }

        let n = E::Newtype(-1);
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><Newtype>-1</Newtype>"#;
        assert_eq!(to_string(&n).unwrap(), expected);

        let u = E::Unit;
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><Unit/>"#;
        assert_eq!(to_string(&u).unwrap(), expected);

        let s = E::Struct { a: 10 };
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><E><Struct><a>10</a></Struct></E>"#;
        assert_eq!(to_string(&s).unwrap(), expected);

        let t = E::Tuple(100, 200);
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><Tuple>100 200</Tuple>"#;
        assert_eq!(to_string(&t).unwrap(), expected);
    }

    /// UT test to serialize object
    ///
    /// # Title
    /// ut_serialize_object
    ///
    /// # Brief
    /// 1.Uses `to_string` method to serialize object.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_serialize_object() {
        let mut hash = HashMap::new();
        hash.insert("apple", 1);
        let expected = r#"<?xml version="1.0" encoding="UTF-8"?><apple>1</apple>"#;
        assert_eq!(to_string(&hash).unwrap(), expected);
        hash.insert("banana", 2);
        assert!(to_string(&hash).is_ok());
    }

    /// UT test to for error scenario
    ///
    /// # Title
    /// ut_error_scenario
    ///
    /// # Brief
    /// 1.Uses `to_string` for error scenario.
    /// 2.Checks if the test results are correct.
    ///
    #[test]
    fn ut_error_scenario() {
        let mut writer = AuxiliaryWriter { output: Vec::new() };
        assert!(writer.flush().is_ok());

        let mut serializer = Serializer::new(writer);
        serializer.tag_stack_top += 1;
        assert!(serializer.obtain_current_tag().is_err());
    }
}
